package org.JWCB.common.security.handler;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.JWCB.common.core.domain.vo.R;
import org.JWCB.common.core.enums.ResultCode;
import org.JWCB.common.core.exception.ServiceException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 请求方法不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
         log.info("请求地址'{}',请求方式不支持.", requestURI, e);
        return R.fail(ResultCode.FAILED_REQUEST_METHOD_NO_SUPPORTED);
    }


    /**
     * 请求参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public R<Void> handleBindException(BindException e) {
        log.error(e.getMessage());
        String message = join(e.getAllErrors(),
                DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        return R.fail(ResultCode.FAILED_PARAMS_VALIDATE.getCode(), message);
    }

    /**
     * 拼接
     */
    private <E> String join(Collection<E> collection, Function<E, String>
            function, CharSequence delimiter) {
        if (CollUtil.isEmpty(collection)) {
            return StrUtil.EMPTY;
        }
        return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
    }
    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R<?> handleServiceException(ServiceException e,HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.info("请求地址'{}',发生业务异常: {}", requestURI, e.getResultCode().getMsg());
        return R.fail(e.getResultCode());
    }


    /**
     * 请求参数类型转换异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R<?> handleMethodArgumentTypeMismatchException(HttpMessageNotReadableException e,HttpServletRequest request) {
        String requestURI = request.getRequestURI();

        log.info("请求地址'{}',参数格式错误", requestURI);
        return R.fail(ResultCode.FAILED_PARAMS_VALIDATE.getCode(),"参数格式错误: "+e.getMessage());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public R<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e,HttpServletRequest request) {
        String requestURI = request.getRequestURI();

        log.info("请求地址'{}',参数格式错误", requestURI);
        return R.fail(ResultCode.FAILED_PARAMS_VALIDATE.getCode(),"参数格式错误: "+e.getMessage());
    }
    /**
     * 拦截运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
         log.error("请求地址'{}',发生异常.", requestURI, e);
        return R.fail(ResultCode.ERROR);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public R<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return R.fail(ResultCode.FILE_TOO_BIG);
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<?> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        return R.fail(ResultCode.FILE_TOO_BIG);
    }
    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生异常.", requestURI, e);
        return R.fail(ResultCode.ERROR);
    }


}
